package com.csyaonie.android;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.csyaonie.android.dto.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpActivity extends AppCompatActivity {

    private Button sendbt1;
    private Button sendbt2;
    private Button jsonbt1;
    private TextView sendtv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);

        sendbt1 = findViewById(R.id.sendbt1);
        sendbt2 = findViewById(R.id.sendbt2);
        jsonbt1 = findViewById(R.id.jsonbt1);
        sendtv1 = findViewById(R.id.sendtv1);

        sendbt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequetWithHttpURLConnnection();
            }
        });
        sendbt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequetWithOkHttp();
            }
        });
        jsonbt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequetWithOkHttpJson();
            }
        });
    }

    private void sendRequetWithHttpURLConnnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader reader = null;
                HttpURLConnection httpURLConnection = null;

                try {
                    URL url = new URL("https://www.baidu.com");
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setReadTimeout(5000);
                    httpURLConnection.setReadTimeout(5000);
                    InputStream is = httpURLConnection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    showResponse(sb.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void sendRequetWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("https://www.baidu.com");
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    showResponse(response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendRequetWithOkHttpJson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://192.168.210.159:8081/get_data.json");
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    showResponseWithGson    (response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendtv1.setText(str);
            }
        });
    }

    private void showResponseWithJSONObject(final String jsonData) {
        runOnUiThread(()-> {
            try {
                JSONArray jsonArray = new JSONArray(jsonData);
                int len = jsonArray.length();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < len; i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String id = jsonObject.getString("id");
                    String name = jsonObject.getString("name");
                    String version = jsonObject.getString("version");
                    sb.append("id" + id + ",name" + name + ",version" + version + "\n");
                }
                sendtv1.setText(sb.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }

    private void showResponseWithGson(final String jsonData) {
        runOnUiThread(()-> {
            try {
                Gson gson = new Gson();
                StringBuilder sb = new StringBuilder();
                List<Person> personList = gson.fromJson(jsonData,
                        new TypeToken<List<Person>>() {
                        }.getType());
                for (Person person : personList) {
                    sb.append("id" + person.getId() + ",name" + person.getName() + ",version" + person.getVersion() + "\n");
                }
                sendtv1.setText(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}